package com.dcy.znoa.common.util.http;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HttpRequestUtils {

    public static final Pattern IE_PATTERN = Pattern.compile("^.+(MSIE\\s\\d+\\.\\d+).+$");
    public static final Pattern FF_PATTERN = Pattern.compile("^.+(Firefox/\\d+\\.\\d+(\\.\\d+)?)$");
    public static final Pattern CHROME_PATTERN = Pattern.compile("^.+(Chrome/\\d+(\\.\\d+)?(\\.\\d+)?(\\.\\d+)?).+$");
    public static final Pattern SAFARI_PATTERN = Pattern.compile("^.+(Safari/\\d+\\.\\d+(\\.\\d+)?)$");

    public static String getStringParameter(final HttpServletRequest request, final String name, final String defaultValue) {
        if (request.getParameterMap().containsKey(name))
            return request.getParameter(name);
        else return defaultValue;
    }

    public static int getIntegerParameter(final HttpServletRequest request, final String name, final int defaultValue) {
        if (request.getParameterMap().containsKey(name))
            try {
                return Integer.parseInt(request.getParameter(name));
            } catch (Throwable t) {
                return defaultValue;
            }
        else return defaultValue;
    }

    public static String getClientName(String agent) {
        if (agent != null && !"".equals(agent.trim())) {
            Matcher matcher = IE_PATTERN.matcher(agent);
            if (matcher.matches())
                return matcher.group(1);

            matcher = FF_PATTERN.matcher(agent);
            if (matcher.matches())
                return matcher.group(1);

            matcher = CHROME_PATTERN.matcher(agent);
            if (matcher.matches())
                return matcher.group(1);

            matcher = SAFARI_PATTERN.matcher(agent);
            if (matcher.matches())
                return matcher.group(1);
        }

        return agent;
    }

    public static long getLongParameter(HttpServletRequest request, String key) {
        if (request.getParameterMap().containsKey(key))
            try {
//                return Long.valueOf(request.getParameter(key));
                return Long.parseLong(key);
            } catch (NumberFormatException e) {
                return -1L;
            }
        else
            return -1L;
    }

}